package com.cn.longdistancebusstation.registerAndLogin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Result;
import com.google.gson.Gson;

import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.utils.SMSLog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2018/1/17.
 */

public class VerifyActivity extends BaseActivity implements View.OnClickListener{
    private EditText mPhoneEditText;
    private EditText mVerifyCodeEditText;
    private TextView get_verify_code;
    private Button btn_next;
    private Context ctx;
    int COUNT_DOWN = 60;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify);
        getTitleTextView().setText("手机号验证");
        ctx=VerifyActivity.this;
        initview();
        registerBroadcast();
    }
    private void initview() {
        /*
         * 防止键盘挡住输入框
         * 不希望遮挡设置activity属性 android:windowSoftInputMode="adjustPan"
         * 希望动态调整高度 android:windowSoftInputMode="adjustResize"
         */
        getWindow().setSoftInputMode(WindowManager.LayoutParams.
                SOFT_INPUT_STATE_HIDDEN);
        //锁定屏幕
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mPhoneEditText =(EditText)findViewById(R.id.verify_et_phone_num);
        mVerifyCodeEditText =(EditText)findViewById(R.id.verify_et_enter_verificode);
        get_verify_code=(TextView)findViewById(R.id.verify_btn_get_verification_code);
        get_verify_code.setOnClickListener(this);
        btn_next=(Button)findViewById(R.id.verify_next);
        btn_next.setOnClickListener(this);
        //启动短信验证
        SMSSDK.initSDK(this,"23626de972632","7378e06fb9f365826f4d8f4001116cce");
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        // 注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);

    }

    private void checkPhoneNumber() {
        String number= mPhoneEditText.getText().toString().trim();
        showHud();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<Result> call=httpService.checkPhoneIsExist(number);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                hideHud();
                Gson gson=new Gson();
                Result result=response.body();
                Boolean isSuccess=result.getHead().getSuccess();
                if(isSuccess){
                    Toast.makeText(VerifyActivity.this,"该手机号还未注册",Toast.LENGTH_SHORT).show();
                    btn_next.setClickable(false);

                }else{
                    getVerifyCode();
                }
            }
            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                hideHud();
                Toast.makeText(VerifyActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 验证码
     */
    public void getVerifyCode(){
        String strPhone = mPhoneEditText.getText().toString();
        SMSSDK.initSDK(ctx, strPhone, mVerifyCodeEditText.getText().toString());
        SMSSDK.getVerificationCode("86", strPhone);
    }
    /*
    * 开始倒计时
    * */
    private void startCountDown(){
        get_verify_code.setClickable(false);
        get_verify_code.setText("重新发送(" + COUNT_DOWN + ")");
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (; COUNT_DOWN > 0; COUNT_DOWN--) {
                    handler.sendEmptyMessage(-9);
                    if (COUNT_DOWN <= 0) {
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                handler.sendEmptyMessage(-8);
            }
        }).start();
    }
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                get_verify_code.setText("重新发送(" + COUNT_DOWN + ")");
            } else if (msg.what == -8) {
                get_verify_code.setText("获取验证码");
                get_verify_code.setClickable(true);
                COUNT_DOWN = 60;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                        Intent intent=new Intent(VerifyActivity.this,ResettingPasswordActivity.class);
                        intent.putExtra("phone", mPhoneEditText.getText().toString());
                        startActivity(intent);
                        finish();
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        startCountDown();
                        Toast.makeText(getApplicationContext(), "验证码已经发送",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }
                else{
                    try {
                        int status = 0;
                        ((Throwable) data).printStackTrace();
                        Throwable throwable = (Throwable) data;

                        JSONObject object = new JSONObject(
                                throwable.getMessage());
                        String des = object.optString("detail");
                        status = object.optInt("status");
                        if (!TextUtils.isEmpty(des)) {
                            Toast.makeText(VerifyActivity.this, des, Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        SMSLog.getInstance().w(e);
                    }
                }
            }
        }
    };

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
        String telRegex = "^1+[3578]+\\d{9}";
        return mobileNums.matches(telRegex);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.verify_next:
                next();
                break;
            case R.id.verify_btn_get_verification_code:
                String strPhone= mPhoneEditText.getText().toString().trim();
                if(TextUtils.isEmpty(strPhone)){
                    Toast.makeText(VerifyActivity.this,"手机号码或验证码不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                //验证手机号格式
                if(!isMobileNO(strPhone)){
                    Toast.makeText(VerifyActivity.this, "无效的手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                //检查手机号是否已注册
                checkPhoneNumber();
                break;
        }
    }

    private void next() {
        String strPhone= mPhoneEditText.getText().toString();
        String strVerifyCode= mVerifyCodeEditText.getText().toString();
        if(strPhone.equals(" ")){
            Toast.makeText(VerifyActivity.this,"手机号和验证码不能为空",Toast.LENGTH_SHORT).show();
        }else{
            SMSSDK.submitVerificationCode("86", strPhone, strVerifyCode);
        }
    }
    MyReceiver receiver;
    private void registerBroadcast() {
        // 注册广播接收者
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("exit_current_boundary");
        this.registerReceiver(receiver,filter);
    }
    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("exit_current_boundary")){
                finish();
            }
        }
    }

}
